package priv.books.service;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import priv.books.mapper.OrderDetailMapper;
import priv.books.pojo.Books;
import priv.books.mapper.BooksMapper;
import priv.books.pojo.OrderDetail;

@Service
public class BooksService extends ServiceImpl<BooksMapper, Books> {

    @Autowired
    private BooksMapper booksMapper;

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private OrderDetailService orderDetailService;

    /**
     * 查询书籍信息
     * @param books
     * @return
     */
    public List<Books> getAllInfo(Books books) {
        return booksMapper.getAllInfo(books);
    }

    /**
     * 根据多ID查询
     * @param ids
     * @return
     */
    public List<Books> getByIds(String ids) {
        return booksMapper.selectBatchIds(StrUtil.split(ids, ',', true, true));
    }

    /**
     * 根据多ID查询
     * @param ids
     * @return
     */
    public List<Books> getByIds(List<Integer> ids) {
        return booksMapper.selectBatchIds(ids);
    }

    /**
     * 更新书籍信息
     * @param books
     * @return
     */
    public boolean updateInfo(Books books) {
        // 修改书籍信息, 同时更新绑定的相关外键信息
        // 首先查询未修改之前的数据
        Books booksInfo = booksMapper.selectOne(new QueryWrapper<Books>().eq("id", books.getId()));
        // 根据书籍名字查询出订单详情中的相关数据, 之后更新订单详情中的书籍名
        List<OrderDetail> orderDetails = orderDetailMapper.selectList(new QueryWrapper<OrderDetail>().eq("books_name", booksInfo.getBookName()));
        if(orderDetails != null && orderDetails.size() > 0) {
            orderDetails.forEach(item -> {
                item.setBooksName(books.getBookName());
            });
            // 更新订单详情
            boolean updateOrderDetail = orderDetailService.updateBatchById(orderDetails);
            if(!updateOrderDetail) {
                throw new RuntimeException("更新相关联的数据出现错误！");
            }
        }
        // 更新图书信息
        return this.updateById(books);
    }
}
